const mongoose = require('mongoose');
const User = require('../models/user.model');
const jwt=require('jsonwebtoken');
//新增
exports.create = function (req, res, next) {
    const user = new User(req.body);
    user.save().then((data) => {
        res.json(data);
    });
}

exports.update = function (req, res, next) {
    const id = req.params.id;
    User.findByIdAndUpdate(id, {
            $set: req.body
        }, {
            new: false
        })
        .then(data => {
            res.json(data); //这里返回的数据z是修改之前的数据，不是修改之后的数据
        });
}
exports.remove = function (req, res, next) {
    const id = req.params.id;
    User.findByIdAndDelete(id, (err, data) => {
        res.json(data);
    })
}

exports.list = function (req, res, next) {
	console.log(req.token);
	jwt.verify(req.token,'secret',(err,authData)=>{
		if(err){
			console.log(err);
			res.sendStatus(403);
		}else{
			var page = req.body.page ? req.body.page : 1;
		    var rows = req.body.rows ? req.body.rows : 5;
		
		    var queryCondition = {};  //查询条件
		    if(req.body.name && req.body.name.trim().length>0){
		        name           = req.body.name;
		        queryCondition = {
		            "name": new RegExp(name,"i")
		        }
		    }
		    User.paginate(queryCondition, {
		        page : +page,
		        limit: +rows
		    }, function (err, result) {
		        result.rows = result.docs;
		        delete result.docs
		        res.json(result);
		    });
		}
		})
    
}

exports.getData = function (req, res, next) {
    var id = req.params.id;
    User.findById(id).then(data => {
        res.json(data);
    })
}
exports.removes = function (req, res, next) {
    var ids = req.body.ids.split(',');
    if (ids.length > 0) {
        User.remove({
            _id: {
                $in: ids
            }
        }).then(data => {
            res.json({
                'message': 'delete ok',
                status   : 200
            })
        })
    }
}

exports.login = function (req, res, next) {
    var name=req.body.name;
    var password=req.body.password;
    User.find({name,password}).then(data=>{
    	console.log(data);
    	if(data.length>0){
    		jwt.sign({data},'secret',(err,token)=>{
	    		res.json({token});
	    	})
    	}
    	
    })
}